define(['./viewbag', './defineTheme'], function () {
    var app = angular.module('App');
    app.factory('chartsFactory', ['$http', '$q', 'defineTheme', '$rootScope', '$timeout', '$compile', '$filter', 'viewbag',
        function ($http, $q, defineTheme, $rootScope, $timeout, $compile, $filter, viewbag) {
            defineTheme.light();
            var botoomBar_height = -1;
            //制保留2位小数，如：2，会在2后面补上00.即2.00  
            function toDecimal2(x) {
                var f = Math.round(x * 100) / 100;
                var s = f.toString();
                var rs = s.indexOf('.');
                if (rs < 0) {
                    rs = s.length;
                    s += '.';
                }
                while (s.length <= rs + 2) {
                    s += '0';
                }
                return s;
            }

            //缩放图表
            function zoomChart(domId) {
                domId.indexOf('#') < 0 && (domId = '#' + domId);
                var zoomed = false;
                var chart = $(domId).highcharts();
                var xExtremes = chart.xAxis[0].getExtremes();
                var zoomStep = Math.floor((xExtremes.max - xExtremes.min) / 6);
                var curMin = xExtremes.min;
                var curMax = xExtremes.max;
                var animiation = chart.series[0].data.length < 100;
                $(domId).on('mousewheel DOMMouseScroll', function (event) {
                    var mouseLeft = Math.floor(zoomStep * (event.offsetX - chart.plotLeft) / chart.plotWidth);
                    var mouseRight = Math.floor(zoomStep * (chart.plotWidth - event.offsetX + chart.plotLeft) / chart.plotWidth);
                    if (event.originalEvent.wheelDelta > 0 || event.originalEvent.detail < 0) {
                        curMin = curMin + mouseLeft;
                        curMax = curMax - mouseRight;
                        chart.xAxis[0].setExtremes(curMin, curMax, true, animiation);
                        zoomed = true;
                    } else {
                        curMin = curMin - mouseLeft;
                        curMax = curMax + mouseRight;
                        if (curMin < xExtremes.min || curMax > xExtremes.max) {
                            chart.zoom();
                            curMin = xExtremes.min;
                            curMax = xExtremes.max;
                            zoomed = false;
                        } else {
                            chart.xAxis[0].setExtremes(curMin, curMax, true, animiation);
                            zoomed = true;
                        }
                    }
                });
            };

            function getYInterval(max, min) {
                var yInterval = Math.floor(((max - min) / 20));
                yInterval = yInterval === 0 ? 5 : yInterval * 5;
                return yInterval;
            }

            var fac = {
                botoomBarHeight: function () {
                    if (botoomBar_height > 0) {

                    } else {
                        botoomBar_height = $('#bottomBar').height() - $('#bottomBar .ng-isolate-scope').first().height();
                    }
                    return botoomBar_height;
                },
                destroy: function (domId) {
                    var chart = $(domId).highcharts();
                    if (chart) {
                        $(domId).off('mousewheel DOMMouseScroll');
                        chart.destroy();
                    }
                },
                createAutoSurveyAllLastValues: function (domId, data) {
                    var defer = $q.defer();
                    var dom = $(domId);
                    var chart = dom.highcharts();
                    if (chart) {
                        chart.destroy();
                    }
                    defineTheme.dark();
                    $(domId).highcharts({
                        chart: {
                            height: botoomBar_height,
                            type: 'line',
                            borderColor: "transparent",
                            width: dom.width() ? dom.width() : document.body.clientWidth,
                            style: {
                                fontFamily: '"Microsoft Yahei", Verdana', // default font
                                fontSize: '11px'
                            },
                            spacingLeft: 3,
                            marginTop: 6,
                            spacingRight: 8
                        },
                        colors: ["#71B7DD"],
                        plotOptions: {
                            line: {
                                pointPlacement: 'on',
                                lineWidth: 2,
                                marker: {
                                    radius: 3
                                }
                            }
                        },
                        exporting: {
                            enabled: false
                        },
                        credits: {
                            enabled: false
                        },
                        title: {
                            align: 'center',
                            text: "本次变化",
                            x: 30,
                            style: {
                                color: "#eee",
                                fontSize: "16px",
                                fontWeight: "600"
                            }
                        },
                        xAxis: {
                            categories: (function () {
                                return data.map(function (item) {
                                    return item.ringNumber || item.name;
                                });
                            })(),
                            gridLineColor: "#fff",
                            labels: {
                                style: {
                                    color: '#eee'
                                }
                            },
                            tickmarkPlacement: 'on',
                            lineColor: '#aaa'
                        },
                        yAxis: {
                            lineWidth: 1,
                            gridLineColor: "#3E3E40",
                            lineColor: '#fff',
                            title: {
                                text: ''
                            },
                            minTickInterval: 1,
                            labels: {
                                x: -10,
                                style: {
                                    color: '#eee'
                                }
                            }
                        },
                        tooltip: {
                            headerFormat: '<b>{point.key}</b>:',
                            pointFormat: '{point.y}mm'
                        },
                        legend: {
                            enabled: false
                        },
                        series: [{
                            name: ' ',
                            data: (function () {
                                return data.map(function (item) {
                                    return item.value;
                                });
                            })()
                        }]
                    });
                    defer.resolve(null);
                    return defer.promise;
                },
                /** 制作混合查询图表 */
                createMixChangeChart: function (domId, dataSet) {
                    fac.destroy(domId);
                    defineTheme.dark();
                    var series = dataSet.data.map(function (mixChange) {
                        var data = mixChange.diff.map(function (result) {
                            return {
                                x: result.mileage,
                                y: result.value === "NaN" ? null : result.value,
                                period: mixChange.startDate + '至' + mixChange.endDate,
                                ptName: result.name,
                                remark: result.remark || "",
                                prjId: mixChange.prjId,
                                corp: mixChange.corp,
                                prjName: mixChange.prjName,
                                marker: result.remark && {
                                    radius: 7,
                                    lineWidth: 3
                                }
                            };
                        });
                        var yValues = data.map(function (item) {
                            return item.y
                        });
                        return {
                            name: mixChange.prjName,
                            data: data,
                            max: Math.max.apply(Math, yValues),
                            min: Math.min.apply(Math, yValues)
                        };
                    });
                    var yMax = Math.max.apply(Math, series.map(function (item) {
                        return item.max;
                    }));
                    var yMin = Math.min.apply(Math, series.map(function (item) {
                        return item.min;
                    }));
                    $(domId).highcharts({
                        chart: {
                            type: 'line',
                            borderColor: "transparent",
                            style: {
                                fontFamily: '"Microsoft Yahei", Verdana', // default font
                                fontSize: '11px'
                            },
                            spacing: [10, 10, 10, 10],
                            margin: [10, 10, 28, 35],
                            backgroundColor: "#333",
                            panning: true
                        },
                        colors: ["#E63628", "#71B7DD", "#FFD455", "#49B159", "#ff0066", "#AAEEEE", "#A3FC4F", "#eeaaee", "#F4F78D", "#0B87D1"],
                        plotOptions: {
                            line: {
                                pointPlacement: 'on',
                                lineWidth: 2,
                                marker: {
                                    radius: 3
                                },
                                dataLabels: {
                                    enabled: true,
                                    color: "#ddd",
                                    useHTML: true,
                                    zIndex: 2,
                                    formatter: function () {
                                        if (this.point.remark) {
                                            var htmlStr = '<div style="color:#ddd;z-index:40;width:1em;white-space: normal;font-size:12px;">' + Array.prototype.join.call(this.point.remark, ' ') + '</div>';
                                            return htmlStr;
                                        } else return '';
                                    }
                                },
                                events: {
                                    show: function () {
                                        var prjName = this.name;
                                        $rootScope.$broadcast('mixChartSeriesShow', prjName);
                                    },
                                    hide: function () {
                                        var prjName = this.name;
                                        $rootScope.$broadcast('mixChartSeriesHide', prjName);
                                    }
                                },
                                point: {
                                    events: {
                                        mouseOver: function (event) {
                                            var pt = this;
                                            $rootScope.$broadcast('mixChartPointHover', {
                                                ptName: pt.ptName,
                                                prjId: pt.prjId
                                            });
                                        },
                                        mouseOut: function (event) {
                                            var pt = this;
                                            $rootScope.$broadcast('mixChartPointLeave', {
                                                ptName: pt.ptName,
                                                prjId: pt.prjId
                                            });
                                        },
                                        click: function (event) {
                                            var pt = this;
                                            $rootScope.$broadcast('mixChartPointClick', {
                                                ptName: pt.ptName,
                                                prjId: pt.prjId
                                            });
                                        }
                                    }
                                }
                            }
                        },
                        exporting: {
                            enabled: false,
                            allowHTML: true
                        },
                        credits: {
                            enabled: false
                        },
                        title: {
                            align: 'left',
                            text: dataSet.title,
                            x: 30,
                            style: {
                                color: "#eee",
                                fontSize: "15px",
                                fontWeight: "600",
                                letterSpacing: "2px"
                            }
                        },
                        subtitle: {
                            align: 'right',
                            useHTML: true,
                            text: "未显示的项目表示该该项目在时间段内并无数据或者时间差距大于2个月",
                            style: {
                                color: "#aaa",
                                fontSize: "9px",
                                fontWeight: 300,
                                fontFamily: "serif",
                                letterSpacing: "1px"
                            },
                            y: $(domId).height() - 47
                        },
                        xAxis: {
                            gridLineColor: "#fff",
                            labels: {
                                formatter: function () {
                                    var num = this.value - 0;
                                    var k = Math.floor(this.value / 1000);
                                    var prefix = "K";
                                    if (dataSet.location.indexOf('上行线') >= 0) {
                                        prefix = "SK";
                                    } else if (dataSet.location.indexOf('下行线') >= 0) {
                                        prefix = "XK";
                                    }
                                    return prefix + k.toString() + '+' + ('00' + (num - k * 1000).toFixed(1)).slice(-5);
                                },
                                style: {
                                    color: '#eee'
                                },
                                staggerLines: 1
                            },
                            tickmarkPlacement: 'on',
                            lineColor: '#999',
                            tickLength: 4
                        },
                        yAxis: {
                            lineWidth: 1,
                            // gridLineColor: "#2f2f2f",
                            lineColor: '#999',
                            title: {
                                text: ''
                            },
                            minTickInterval: 5,
                            max: yMax + 2,
                            min: yMin - 2,
                            tickInterval: 10,
                            tickLength: 5,
                            minorTickLength: 5,
                            minorTickWidth: 1,
                            labels: {
                                x: -10,
                                style: {
                                    color: '#eee'
                                }
                            }
                        },
                        tooltip: {
                            useHTML: true,
                            formatter: function () {
                                return '<table class="ui table">' +
                                    '<tr><td>项目 :</td><td>' + this.point.prjName + '</td></tr>' +
                                    '<tr><td>单位 :</td><td>' + this.point.corp + '</td></tr>' +
                                    '<tr><td>点号 :</td><td>' + this.point.ptName + '</td></tr>' +
                                    '<tr><td>时间 :</td><td>' + this.point.period + '</td></tr>' +
                                    '<tr><td>变化 :</td><td>' + this.point.y + 'mm</td></tr>' +
                                    '</table>';
                            }
                        },
                        legend: {
                            align: 'right',
                            verticalAlign: 'top',
                            floating: true,
                            borderWidth: 0,
                            y: -6
                        },
                        series: series
                    });
                    var chart = $(domId).highcharts();
                    dataSet.data.forEach(function (data, index) {
                        if (!data.qualify) {
                            chart.series[index].hide();
                        }
                    });
                    zoomChart(domId);
                    return chart;
                },
                createAutoSurveyOnePointRecentValues: function (domId, dataSet) {
                    var defer = $q.defer();
                    var chart = $(domId).highcharts();
                    if (chart) {
                        chart.destroy();
                    }
                    var dom = $(domId);
                    defineTheme.dark();
                    $(domId).highcharts({
                        chart: {
                            height: botoomBar_height,
                            type: 'line',
                            borderColor: "transparent",
                            width: dom.width() ? dom.width() : document.body.clientWidth,
                            // width: document.documentElement.clientWidth - 4,
                            style: {
                                fontFamily: '"Microsoft Yahei", Verdana', // default font
                                fontSize: '11px'
                            },
                            spacingLeft: 3,
                            marginTop: 6,
                            spacingRight: 8
                        },
                        colors: ["#71B7DD"],
                        plotOptions: {
                            line: {
                                pointPlacement: 'on',
                                lineWidth: 2,
                                marker: {
                                    radius: 3
                                }
                            }
                        },
                        exporting: {
                            enabled: false
                        },
                        credits: {
                            enabled: false
                        },
                        title: {
                            align: 'center',
                            text: dataSet.name + "(" + dataSet.ringNumber + "环)",
                            x: 30,
                            style: {
                                color: "#eee",
                                fontSize: "16px",
                                fontWeight: "600"
                            }
                        },
                        xAxis: {
                            categories: (function () {
                                return dataSet.list.map(function (item) {
                                    return item.time;
                                });
                            })(),
                            gridLineColor: "#fff",
                            labels: {
                                style: {
                                    color: '#eee'
                                }
                            },
                            tickmarkPlacement: 'on',
                            lineColor: '#aaa'
                        },
                        yAxis: {
                            lineWidth: 1,
                            gridLineColor: "#3E3E40",
                            lineColor: '#fff',
                            title: {
                                text: ''
                            },
                            tickInterval: 0.001,
                            labels: {
                                x: -10,
                                style: {
                                    color: '#eee'
                                }
                            }
                        },
                        tooltip: {
                            headerFormat: '<b>{point.key}</b>:',
                            pointFormat: '{point.y}mm'
                        },
                        legend: {
                            enabled: false
                        },
                        series: [{
                            name: ' ',
                            data: (function () {
                                return dataSet.list.map(function (item) {
                                    return item.value;
                                });
                            })()
                        }]
                    });
                    defer.resolve(null);
                    return defer.promise;
                },
                //用户选择了一系列时间之后,绘制多时间的变化曲线
                createPointsChartListByLocation: function (domId, dataSet, bindMap) {
                    domId.indexOf('#') < 0 && (domId = '#' + domId);
                    if (typeof (bindMap) === 'undefined') {
                        bindMap = true;
                    }
                    var defer = $q.defer();
                    var dom = $(domId);
                    fac.destroy(domId);
                    var xAxisInterval = 1;
                    var base = 20;
                    if ($rootScope.smallScreen) {
                        base = 10;
                    }
                    if (dataSet.dataList[0].length > base) {
                        xAxisInterval = Math.floor(dataSet.dataList[0].length / base) + 3;
                    } else {
                        xAxisInterval = 8;
                    }
                    var pointEvent = bindMap ? {
                        events: {
                            mouseOver: function (event) {
                                var map = viewbag.map;
                                if (map.viewState === 'active') {
                                    var ptName = this.name;
                                    map.fireEvent('makerHoverActive', {
                                        map: map,
                                        ptName: ptName
                                    });
                                }
                            },
                            mouseOut: function (event) {
                                var map = viewbag.map;
                                if (map.viewState === 'active') {
                                    var ptName = this.name;
                                    map.fireEvent('makerHoverInactive', {
                                        map: map,
                                        ptName: ptName
                                    });
                                }
                            },
                            click: function (event) {
                                var ptName = this.name;
                                fac.openSinglePointModal(ptName);
                            }
                        }
                    } : {};
                    var series = dataSet.dataList.map(function (dataItems, listIndex) {
                        return {
                            name: dataItems[0].time,
                            data: dataItems.map(function (item, itemIndex) {
                                return {
                                    x: dataSet.drawByMile ? item.mileageNumber : undefined,
                                    y: item.value,
                                    time: item.time,
                                    name: item.name,
                                    remark: item.remark,
                                    ringNumber: item.ringNumber,
                                    mileage: item.mileage
                                };
                            })
                        };
                    });
                    var partialSeries = [];
                    //如果点数大于200,抽稀显示
                    if (series.length > 0 && series[0].data.length > 200) {
                        var seriesStep = Math.round(series[0].data.length / 80);
                        partialSeries = series.map(function (itemArr) {
                            return {
                                name: itemArr.name,
                                data: itemArr.data.filter(function (item, index) {
                                    return index % seriesStep === 0 || series[0].data[index].remark;
                                })
                            }
                        });
                    }
                    defineTheme.custom();
                    $(domId).highcharts({
                        chart: {
                            type: 'line',
                            width: dom.width() ? dom.width() : document.body.clientWidth,
                            height: botoomBar_height,
                            panning: true
                        },
                        title: {
                            text: dataSet.title
                        },
                        xAxis: {
                            type: dataSet.drawByMile ? 'linear' : 'category',
                            labels: {
                                step: dataSet.drawByMile ? xAxisInterval : 1,
                                formatter: function () {
                                    if (dataSet.drawByMile) {
                                        var num = this.value - 0;
                                        var k = Math.floor(this.value / 1000);
                                        return k.toString() + 'K+' + (num - k * 1000).toFixed(2);
                                    } else {
                                        return this.value;
                                    }
                                }
                            },
                            tickInterval: xAxisInterval
                        },
                        yAxis: {
                            title: {
                                text: ''
                            },
                            minTickInterval: 1,
                            max: dataSet.max === null ? null : ((dataSet.max - dataSet.min > 5) ? dataSet.max + 2 : dataSet.max + 3),
                            min: dataSet.max === null ? null : ((dataSet.max - dataSet.min > 5) ? dataSet.min - 2 : dataSet.min - 3)
                        },
                        tooltip: {
                            useHTML: true,
                            formatter: function () {
                                return '<table class="ui table">' +
                                    '<tr><td>点号 :</td><td>' + this.point.name + '</td></tr>' +
                                    '<tr><td>时间 :</td><td>' + this.point.time + '</td></tr>' +
                                    '<tr style="border-bottom: 1px solid #444;"><td>累计 :</td><td>' + toDecimal2(this.point.y) + 'mm</td></tr>' +
                                    '<tr><td>环号 :</td><td>' + this.point.ringNumber + '</td></tr>' +
                                    '<tr><td>里程 :</td><td>' + this.point.mileage + '</td></tr>' +
                                    '</table>';
                            }

                        },
                        plotOptions: {
                            line: {
                                turboThreshold: 1500,
                                dataLabels: {
                                    enabled: true,
                                    useHTML: true,
                                    zIndex: 2,
                                    allowOverlap: true,
                                    formatter: function () {
                                        if (this.point.remark) {
                                            var htmlStr = "";
                                            htmlStr = '<div style="z-index:40;width:1em;white-space: normal;font-size:12px;">' + Array.prototype.join.call(this.point.remark, ' ') + '</div>';
                                            return htmlStr;
                                        } else return '';
                                    }
                                }
                            },
                            series: {
                                cursor: 'pointer',
                                point: pointEvent
                            }
                        },
                        series: partialSeries.length > 0 ? partialSeries : series
                    });
                    function addAllPoint() {
                        setTimeout(function () {
                            if (partialSeries.length >= 0) {
                                var chart = $(domId).highcharts();
                                for (var i = 0; i < chart.series.length; i++) {
                                    chart.series[i].setData(series[i].data);
                                }
                            }
                            zoomChart(domId);
                        }, 800);
                    }
                    addAllPoint();
                    defer.resolve(null);
                    return defer.promise;

                },
                createPointsChartByLocation: function (domId, dataSet, bindMap) {
                    domId.indexOf('#') < 0 && (domId = '#' + domId);
                    if (typeof (bindMap) === 'undefined') bindMap = false;//默认不绑定
                    var defer = $q.defer();
                    var dom = $(domId);
                    fac.destroy(domId);
                    var xAxisInterval = 1;
                    var base = 10;
                    if (dataSet.lastValues.length > base) {
                        xAxisInterval = Math.floor(dataSet.lastValues.length / base) + 3;
                    } else {
                        if (dataSet.drawByMile) {
                            xAxisInterval = 5;
                        } else {
                            xAxisInterval = 1;
                        }
                    }
                    var yInterval = getYInterval(dataSet.max, dataSet.min);
                    var pointEvent = bindMap ? {
                        events: {
                            mouseOver: function (event) {
                                var map = viewbag.map;
                                var ptName = this.name;
                                map.fireEvent('makerHoverActive', {
                                    map: map,
                                    ptName: ptName
                                });
                            },
                            mouseOut: function (event) {
                                var map = viewbag.map;
                                var ptName = this.name;
                                map.fireEvent('makerHoverInactive', {
                                    map: map,
                                    ptName: ptName
                                });
                            },
                            click: function (event) {
                                event.stopPropagation();
                                var ptName = this.name;
                                fac.openSinglePointModal(ptName);
                            }
                        }
                    } : {};
                    var series1 = (function () {
                        return dataSet.lastValues.map(function (item, index) {
                            return {
                                x: dataSet.drawByMile ? item.mileageNumber : undefined,
                                ringNumber: item.ringNumber,
                                mileage: item.mileage,
                                y: item.value,
                                name: item.name,
                                time: dataSet.lastTime,
                                diff: dataSet.curValues[index].value - dataSet.lastValues[index].value
                            };
                        });
                    })();
                    var series2 = (function () {
                        return dataSet.curValues.map(function (item, index) {
                            return {
                                x: dataSet.drawByMile ? item.mileageNumber : undefined,
                                remark: item.remark,
                                mileage: item.mileage,
                                ringNumber: item.ringNumber,
                                y: item.value,
                                name: item.name,
                                time: dataSet.curTime,
                                diff: dataSet.curValues[index].value - dataSet.lastValues[index].value,
                                marker: (function () {
                                    if (item.remark) {
                                        return {
                                            enabled: true,
                                            radius: 5
                                        };
                                    }
                                })()
                            };
                        });
                    })();

                    var marginLeft = Math.round(Math.max(Math.abs(dataSet.max), Math.abs(dataSet.min))).toString().length * 10;
                    var seriesStep = Math.round(series1.length / 80);
                    var config = {
                        chart: {
                            type: 'line',
                            margin: [10, dataSet.drawByMile ? 30 : 10, 30, bindMap ? null : (dataSet.drawByMile ? 30 : marginLeft)],
                            panning: true
                        },
                        title: {
                            text: ""
                        },
                        subtitle: {
                            text: "初始值测于 : " + (dataSet.allTimes.length > 0 ? dataSet.allTimes[dataSet.allTimes.length - 1] : '无'),
                            y: dom.height() - 38
                        },
                        xAxis: {
                            type: dataSet.drawByMile ? 'linear' : 'category',
                            labels: {
                                formatter: function () {
                                    if (dataSet.drawByMile) {
                                        var num = this.value - 0;
                                        var k = Math.floor(this.value / 1000);
                                        var prefix = "K";
                                        if (dataSet.title.match(/下行线/)) {
                                            prefix = "XK";
                                        } else if (dataSet.title.match(/上行线/)) {
                                            prefix = "SK";
                                        }
                                        return prefix + k.toString() + '+' + ('00' + (num - k * 1000).toFixed(1)).slice(-5);
                                    } else {
                                        return this.value;
                                    }
                                },
                                step: dataSet.drawByMile ? 8 : 1
                            },
                            tickInterval: xAxisInterval
                        },
                        yAxis: {
                            title: {
                                text: ''
                            },
                            minTickInterval: dataSet.max - dataSet.min > 20 ? undefined : 1,
                            max: (dataSet.max - dataSet.min > 5) ? dataSet.max + 2 : dataSet.max + 3,
                            min: (dataSet.max - dataSet.min > 5) ? dataSet.min - 2 : dataSet.min - 3,
                            tickInterval: yInterval
                        },
                        tooltip: {
                            useHTML: true,
                            formatter: function () {
                                return '<table class="table">' +
                                    '<tr><td>点号 :</td><td>' + this.point.name + '</td></tr>' +
                                    '<tr><td>时间 :</td><td>' + this.point.time + '</td></tr>' +
                                    '<tr style="border-bottom: 1px solid #444;"><td>累计 :</td><td>' + toDecimal2(this.point.y) + (dataSet.title.search(/倾斜$/g) === -1 ? 'mm' : '&#8240;') + '</td></tr>' +
                                    '<tr><td>本次 :</td><td>' + toDecimal2(this.point.diff) + (dataSet.title.search(/倾斜$/g) === -1 ? 'mm' : '&#8240;') + '</td></tr>' +
                                    '<tr><td>环号 :</td><td>' + this.point.ringNumber + '</td></tr>' +
                                    '<tr><td>里程 :</td><td>' + this.point.mileage + '</td></tr>' +
                                    '</table>';
                            }
                        },
                        plotOptions: {
                            line: {
                                turboThreshold: 2000,
                                animation: true,
                                dataLabels: {
                                    enabled: true,
                                    y: -5,
                                    formatter: function () {
                                        if (this.point.remark) {
                                            var htmlStr = "";
                                            htmlStr = '<div style="z-index:999;white-space:normal;font-weight:300;font-size:12px;">' + Array.prototype.join.call(this.point.remark, ' ') + '</div>';
                                            return htmlStr;
                                        } else return '';
                                    }
                                }
                            },
                            series: {
                                cursor: 'pointer',
                                point: pointEvent,
                                marker: {
                                    lineWidth: 0,
                                    radius: bindMap ? (series1.length > 200 ? 2 : 4) : 3
                                }
                            }
                        },
                        series: [
                            {
                                name: dataSet.lastTime,
                                data: series1.length < 200 ? series1 : series1.filter(function (item, index) {
                                    return index % seriesStep === 0 || series2[index].remark;
                                })
                            }, {
                                name: dataSet.curTime,
                                data: series2.length < 200 ? series2 : series2.filter(function (item, index) {
                                    return index % seriesStep === 0 || item.remark;
                                })
                            }]
                    };
                    $(domId).highcharts(config);
                    function addAllPoint() {
                        setTimeout(function () {
                            if (series1.length >= 200) {
                                var chart = $(domId).highcharts();
                                chart.series[0].setData(series1, false, false, false);
                                chart.series[1].setData(series2, true, false, false);
                            }
                            // zoomChart(domId);
                        }, 800);
                    }
                    addAllPoint();
                    defer.resolve(null);
                    return defer.promise;
                },
                createCorssSearchChart: function (domId, dataSet) {
                    var defer = $q.defer();
                    var dom = $(domId);
                    var chart = dom.highcharts();
                    if (chart) {
                        chart.destroy();
                    }
                    defineTheme.dark();
                    $(domId).highcharts({
                        chart: {
                            type: 'line',
                            borderColor: "transparent",
                            width: dom.width() ? dom.width() : document.body.clientWidth,
                            height: botoomBar_height,
                            style: {
                                fontFamily: '"Microsoft Yahei", Verdana', // default font
                                fontSize: '11px'
                            },
                            spacing: [10, 10, 10, 10],
                            margin: [10, 10, 28, 35],
                            backgroundColor: "#333"
                        },
                        exporting: {
                            enabled: false
                        },
                        credits: {
                            enabled: false
                        },
                        title: {
                            align: 'left',
                            text: dataSet.title,
                            x: 30,
                            style: {
                                color: "#eee",
                                fontSize: "16px",
                                fontWeight: 800
                            }
                        },
                        xAxis: {
                            // categories: (function() {
                            //     return dataSet.lastValues.map(function(item, index) {
                            //         return item.name;
                            //     });
                            // })(),
                            gridLineColor: "#fff",
                            labels: {
                                style: {
                                    color: '#eee'
                                },
                                // step: xAxisInterval,
                                staggerLines: 1
                            },
                            tickmarkPlacement: 'on',
                            lineColor: '#999',
                            tickLength: 4
                        },
                        yAxis: {
                            lineWidth: 1,
                            tickLength: 4,
                            gridLineColor: "#2f2f2f",
                            lineColor: '#999',
                            title: {
                                text: ''
                            },
                            // minTickInterval: dataSet.max - dataSet.min > 20 ? undefined : 1,
                            // max: (dataSet.max - dataSet.min > 5) ? dataSet.max + 2 : dataSet.max + 3,
                            // min: (dataSet.max - dataSet.min > 5) ? dataSet.min - 2 : dataSet.min - 3,
                            // tickInterval: yInterval,
                            labels: {
                                x: -10,
                                style: {
                                    color: '#eee'
                                }
                            }
                        },
                        legend: {
                            align: 'right',
                            verticalAlign: 'top',
                            floating: true,
                            borderWidth: 0,
                            y: -6
                        },
                        tooltip: {
                            useHTML: true,
                            formatter: function () {
                                return '<table class="ui table">' +
                                    '<tr><td>点号 :</td><td>' + this.point.name + '</td></tr>' +
                                    '<tr><td>阶段变化 :</td><td>' + toDecimal2(this.point.y) + 'mm</td></tr>' +
                                    '<tr><td>环号 :</td><td>' + this.point.ringNumber + '</td></tr>' +
                                    '</table>';
                            }
                        },
                        plotOptions: {
                            line: {
                                turboThreshold: 1500
                            },
                            series: {
                                cursor: 'pointer',
                                // point: pointEvent,
                                marker: {
                                    lineWidth: 0
                                }
                            }
                        },
                        series: [{
                            name: dataSet.items[0].name,
                            data: dataSet.items[0].points
                        }, {
                                name: dataSet.items[1].name,
                                data: dataSet.items[1].points
                            }]
                    });
                    defer.resolve(null);
                    return defer.promise;
                },
                createPointsChartByLocationSummary: function (domId, dataSet, width, height) {

                    var defer = $q.defer();
                    var dom = $(domId);
                    var chart = dom.highcharts();
                    if (chart) {
                        chart.destroy();
                    }
                    defineTheme.light();
                    var xAxisInterval = 1;
                    var base = 25;
                    if ($rootScope.smallScreen) {
                        base = 10;
                    }
                    if (dataSet.lastValues.length > base * 2) {
                        xAxisInterval = Math.floor(dataSet.lastValues.length / base) + 3;
                    } else if (dataSet.lastValues.length > base) {
                        xAxisInterval = Math.floor(dataSet.lastValues.length / base) + 2;
                    }

                    var pointEvent = {
                        events: {
                            click: function (event) {
                                var ptName = this.category;
                                fac.openSinglePointModal(ptName);
                            }
                        }
                    };
                    var config = {
                        chart: {
                            type: 'line',
                            borderColor: "#2D7C7C",
                            borderWidth: 0,
                            height: $rootScope.smallScreen ? 250 : 400,
                            style: {
                                fontFamily: '"Microsoft Yahei", Verdana', // default font
                                fontSize: '11px',
                                borderTopLeftRadius: "0px",
                                borderTopRightRadius: "0px",
                                borderBottomLeftRadius: "5px",
                                borderBottomRightRadius: "5px"
                                // borderTop: "5px solid #2D7C7C",
                            },
                            spacing: [40, 40, 40, 40],
                            margin: [30, 30, 50, 50],
                            backgroundColor: "rgb(255,255,255)",
                            borderRadius: 0
                        },
                        exporting: {
                            enabled: false
                        },
                        credits: {
                            enabled: false
                        },
                        title: {
                            align: 'left',
                            text: "",
                            x: 30
                        },
                        xAxis: {
                            categories: (function () {
                                return dataSet.lastValues.map(function (item, index) {
                                    return item.name;
                                });
                            })(),
                            gridLineColor: "transparent",
                            labels: {
                                style: {
                                    color: '#555',
                                    font: '12px'
                                },
                                step: xAxisInterval,
                                staggerLines: 1
                            },
                            tickmarkPlacement: 'on',
                            lineColor: '#444',
                            tickLength: 4
                        },
                        yAxis: {
                            lineWidth: 1,
                            tickLength: 4,
                            gridLineColor: "#f0f0f0",
                            lineColor: '#444',
                            title: {
                                text: ''
                            },
                            minTickInterval: 1,
                            max: (dataSet.max - dataSet.min > 5) ? dataSet.max + 2 : dataSet.max + 3,
                            min: (dataSet.max - dataSet.min > 5) ? dataSet.min - 2 : dataSet.min - 3,
                            labels: {
                                x: -3,
                                style: {
                                    color: '#444',
                                    font: '12px'
                                }
                            }
                        },
                        legend: {
                            align: 'right',
                            verticalAlign: 'top',
                            floating: true,
                            borderWidth: 0,
                            y: -6
                        },
                        tooltip: {
                            headerFormat: '<b>{point.x}</b>:',
                            pointFormat: '{point.y}mm'
                        },
                        plotOptions: {
                            line: {
                                lineWidth: 1,
                                marker: {
                                    radius: 2
                                }
                            },
                            series: {
                                cursor: 'pointer',
                                point: pointEvent,
                                marker: {
                                    lineWidth: 0
                                }
                            }
                        },
                        series: [{
                            name: dataSet.lastTime,
                            data: (function () {
                                return dataSet.lastValues.map(function (item, index) {
                                    return {
                                        name: item.name,
                                        y: item.value,
                                        marker: (function () {
                                            if (item.name === dataSet.maxPointAllTheTime.name) {
                                                return {
                                                    lineWidth: 1,
                                                    enabled: true,
                                                    lineColor: "#111",
                                                    radius: 5
                                                };
                                            } else if (item.name === dataSet.maxPointThisTime.name) {
                                                return {
                                                    enabled: true,
                                                    radius: 5
                                                };
                                            } else {
                                                return {
                                                    enabled: true,
                                                    radius: 2
                                                };
                                            }
                                        })()
                                    };
                                });
                            })()
                        }, {
                                name: dataSet.curTime,
                                data: (function () {
                                    return dataSet.curValues.map(function (item, index) {
                                        return {
                                            name: item.name,
                                            y: item.value,
                                            marker: (function () {
                                                if (item.name === dataSet.maxPointAllTheTime.name) {
                                                    return {
                                                        lineWidth: 1,
                                                        lineColor: "#111",
                                                        enabled: true,
                                                        radius: 5
                                                    };
                                                } else if (item.name === dataSet.maxPointThisTime.name) {
                                                    return {
                                                        enabled: true,
                                                        radius: 5
                                                    };
                                                } else {
                                                    return {
                                                        enabled: true,
                                                        radius: 2
                                                    };
                                                }
                                            })()
                                        };
                                    });
                                })()
                            }]
                    };
                    $(domId).highcharts(config);
                    defer.resolve(null);
                    return defer.promise;
                },
                openSinglePointModal: function (pointName) {
                    var singleChange = null;
                    var prj = $rootScope.curPrj;
                    prj.getSinglePointRecentChanges(pointName).then(function (data) {
                        singleChange = data;
                        var content = $('#singleChartModalCotent').empty();
                        var chartDiv = document.createElement('div');
                        chartDiv.setAttribute('data-point-Name', pointName);
                        chartDiv.setAttribute('data-start-Date', singleChange[0].time.toString());
                        chartDiv.setAttribute('data-end-Date', singleChange[singleChange.length - 1].time.toString());
                        chartDiv.setAttribute('data-single-point-query', '');
                        chartDiv.setAttribute('id', "singlePointQuery");
                        content[0].appendChild(chartDiv);
                        $compile(angular.element(chartDiv))($rootScope);
                        return $timeout(function () { }, 10);
                    }).then(function () {
                        var modal = $('#singleChartModal');
                        modal.modal({
                            detachable: false,
                            onVisible: function () { }
                        });
                        return $timeout(function () {
                            modal.modal('show');
                        }, 300);
                    }).then(function () {
                        return fac.createSinglePointChangesChart('#singleChart', singleChange);
                    });
                },
                createSinglePointChangesChart: function (domId, dataSet) {
                    var defer = $q.defer();
                    var yMax, yMin, yValues;
                    //统计Y值

                    yValues = dataSet.map(function (item) {
                        return item.value;
                    });
                    yMax = Math.max.apply(null, yValues);
                    yMin = Math.min.apply(null, yValues);
                    var yInterval = getYInterval(yMax, yMin);
                    //重新给每个点单赋值工况信息
                    var prj = $rootScope.curPrj;
                    if (prj.mainStatusTimeList && prj.mainStatusTimeList.length > 0) {
                        prj.mainStatusTimeList.forEach(function (item) {
                            //标记为没使用
                            item.used = false;
                        });
                        var statusTimeList = prj.mainStatusTimeList.map(function (item) {
                            return Date.parse(item.time);
                        });

                        dataSet.forEach(function (changeItem) {
                            var tempDiff = statusTimeList.map(function (item) {
                                return Math.abs(Date.parse(changeItem.time) - item);
                            });

                            var min = Math.min.apply(null, tempDiff);
                            if (min < 345600000) {
                                var index = tempDiff.indexOf(min);
                                if (!prj.mainStatusTimeList[index].used) {
                                    changeItem.status = prj.mainStatusTimeList[index].status;
                                    prj.mainStatusTimeList[index].used = true;
                                } else {
                                    changeItem.status = "";
                                }
                            } else {
                                changeItem.status = "";
                            }
                        });
                    }

                    var timeList = dataSet.map(function (item) {
                        return new Date(item.time).getTime();
                    });
                    var min = timeList[0];
                    var max = timeList[timeList.length - 1];
                    var itmeInterval = (max - min) / 5;
                    var chart = $(domId).highcharts();
                    if (chart) {
                        chart.destroy();
                    }
                    defineTheme.custom();
                    chart = $(domId).highcharts({
                        chart: {
                            type: 'line',
                            margin: [70, 10, 40, 40]
                        },
                        title: {
                            align: 'left',
                            text: dataSet[0].name,
                            style: {
                                fontSize: '1.4rem'
                            },
                            y: 32
                        },
                        xAxis: {
                            type: 'datetime',
                            tickmarkPlacement: 'on',
                            tickLength: 4,
                            tickInterval: itmeInterval, // one day
                            labels: {
                                formatter: function () {
                                    var dt = new Date(this.value);
                                    return $filter('date')(dt, 'yyyy-MM-dd');
                                },
                                style: {
                                    fontSize: "12"
                                },
                                y: 28 //-13
                            }
                        },
                        yAxis: {
                            // lineWidth: 0,
                            // tickLength: 0,
                            // gridLineWidth: 1,
                            title: {
                                text: ''
                            },
                            tickInterval: yInterval
                        },
                        legend: {
                            enabled: true,
                            verticalAlign: 'top',
                            align: 'right'
                        },
                        tooltip: {
                            useHTML: "true",
                            formatter: function () {
                                return this.point.time + "<br>" + this.point.y + "mm";
                            }
                        },
                        plotOptions: {
                            line: {
                                animation: false,
                                pointPlacement: 'on',
                                turboThreshold: 2000,
                                dataLabels: {
                                    enabled: true,
                                    useHTML: true,
                                    zIndex: 2,
                                    formatter: function () {
                                        var s = this.point.status;
                                        if (s) {
                                            var htmlStr = '<div style="font-size:12px;z-index:999;width:2em;white-space: normal;">' + Array.prototype.join.call(s, ' ') + '</div>';
                                            return htmlStr;
                                        } else return '';
                                    }
                                },
                                marker: {
                                    enabled: true,
                                    lineWidth: 0,
                                    lineColor: "transparent",
                                    radius: 3
                                },
                                cursor: 'pointer'
                            }
                        },
                        series: [{
                            name: dataSet[0].name,
                            data: (function () {
                                return dataSet.map(function (item) {
                                    return {
                                        x: new Date(item.time),
                                        y: item.value,
                                        status: item.status,
                                        time: item.time
                                    };
                                });
                            })()
                        }]
                    });
                    defer.resolve(null);
                    return defer.promise;
                }
            };
            return fac;
        }
    ]);
});
